package com.bnzj.core.webmvc.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;

import com.bnzj.core.webmvc.util.WebMvcUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.bnzj.core.config.CoreProperties;
import com.bnzj.core.util.JsonUtils;
import com.fasterxml.jackson.databind.node.ObjectNode;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

/**
 * @author barry
 * @date 2019-10-11
 */
@Slf4j
@RestController
@Tag(name = "ExportController", description = "导出文件")
@RequestMapping(value = "/sys/export")
public class ExportController {

    @Resource
    private CoreProperties coreProperties;
    
    @Operation(summary = "导出文件", description = "导出文件")
    @GetMapping(value = "/{fileName}")
    public void exportOfGet(HttpServletRequest request, HttpServletResponse response,
                       @Parameter(description = "文件路径") @NotEmpty @RequestParam String path,
                       @Parameter(description = "文件名") @PathVariable String fileName) {
        export(request, response, path, fileName);
    }

    @Operation(summary = "导出文件", description = "导出文件")
    @PostMapping(value = "/{fileName}")
    public void exportOfPost(HttpServletRequest request, HttpServletResponse response,
                       @Parameter(description = "文件路径") @RequestBody(required = false) String nodeStr,
        @Parameter(description = "文件名") @PathVariable String fileName) {
        String path = null;
        ObjectNode node = null;
        if(nodeStr != null) {
            node = JsonUtils.valueToObjectNode(nodeStr);
        }
        if (node == null) {
            path = request.getParameter("path");
        }else {
            path = node.get("path").asText();
        }
        export(request, response, path, fileName);
    }
    
    private void export(HttpServletRequest request, HttpServletResponse response, String path, String fileName) {
        if(StringUtils.isEmpty(path)){
            response.setStatus(404);
            return;
        }
        response.reset();
        String realPath = "";
        if (!StringUtils.isEmpty(coreProperties.getFileSavePath())) {
            realPath = coreProperties.getFileSavePath();
        }
        File file = new File(realPath + path);
        if(file.exists() && file.isFile()) {
            int buffer = 1024 * 10;
            try (
                ServletOutputStream out = response.getOutputStream();
                InputStream fis = new FileInputStream(file);
                BufferedInputStream bis = new BufferedInputStream(fis, buffer)) {
                fileName = WebMvcUtils.encodeFileName(request.getHeader("User-Agent"), fileName);
                response.setContentType("application/OCTET-STREAM");
                response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
                int read;
                byte[] data = new byte[buffer];
                while ((read = bis.read(data)) != -1) {
                    out.write(data, 0, read);
                }
                out.flush();
            } catch (IOException e) {
                log.error("文件下载异常", e);
            }
        }else {
            response.setStatus(404);
        }
    }
}
